<!DOCTYPE
html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>剪映草稿片段乱序工具</title>
    <style>
        :root {
            --bg-primary: #121212;
            --bg-secondary: #1e1e1e;
            --bg-tertiary: #2d2d2d;
            --bg-card: #252525;
            --text-primary: #e0e0e0;
            --text-secondary: #a0a0a0;
            --accent-primary: #7c4dff;
            --accent-secondary: #5e35b1;
            --success: #4caf50;
            --success-dark: #388e3c;
            --danger: #f44336;
            --danger-dark: #d32f2f;
            --warning: #ff9800;
            --border-color: #444;
            --input-bg: #333;
            --border-radius: 8px;
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', 'Roboto', sans-serif;
            background-color: var(--bg-primary);
            color: var(--text-primary);
            margin: 0;
            padding: 20px;
            min-height: 100vh;
        }

        .container {
            max-width: 600px;
            margin: auto;
            background-color: var(--bg-secondary);
            padding: 25px;
            border-radius: var(--border-radius);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }

        h1 {
            text-align: center;
            color: var(--accent-primary);
            margin-bottom: 25px;
            font-size: 1.8rem;
        }
        
        h2 {
            color: var(--text-primary);
            font-size: 1.2rem;
            margin-bottom: 10px;
        }

        .section {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-secondary);
        }

        .directory-input-container {
            display: flex;
            gap: 5px;
        }

        input[type="text"][readonly] {
            flex: 1;
            border: 1px solid var(--border-color);
            padding: 10px;
            border-radius: 4px;
            background-color: var(--input-bg);
            color: var(--text-primary);
            cursor: default;
        }

        #select-dir-btn {
            width: 100px;
            background-color: var(--accent-primary);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: var(--transition);
        }

        #select-dir-btn:hover {
            background-color: var(--accent-secondary);
        }

        button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            transition: var(--transition);
        }

        #randomize-btn {
            width: 100%;
            background-color: var(--accent-primary);
            color: white;
            padding: 12px;
            font-weight: 500;
        }

        #randomize-btn:hover {
            background-color: var(--accent-secondary);
        }

        button:disabled {
            background-color: var(--bg-tertiary) !important;
            color: var(--text-secondary) !important;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #id-list {
            list-style-type: decimal;
            list-style-position: inside;
            padding: 15px;
            max-height: 250px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            background-color: var(--bg-tertiary);
            min-height: 100px;
            margin-top: 10px;
        }

        #id-list li {
            padding: 5px 0;
            border-bottom: 1px solid var(--border-color);
            font-family: monospace;
            word-break: break-all;
            color: var(--text-secondary);
            line-height: 1.4;
        }

        #id-list li:last-child {
            border-bottom: none;
        }

        #status-message {
            margin-top: 15px;
            font-weight: 500;
            padding: 15px;
            background-color: var(--bg-tertiary);
            border: 1px solid var(--border-color);
            border-radius: var(--border-radius);
            min-height: 50px;
            word-wrap: break-word;
            color: var(--success);
            text-align: center;
        }
        
        .status-error {
            color: var(--danger) !important;
        }
        
        .status-processing {
            animation: pulse 1.5s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 0.6; }
            50% { opacity: 1; }
            100% { opacity: 0.6; }
        }
        
        /* Custom scrollbar for the ID list */
        #id-list::-webkit-scrollbar {
            width: 8px;
        }
        
        #id-list::-webkit-scrollbar-track {
            background: var(--bg-tertiary);
            border-radius: 4px;
        }
        
        #id-list::-webkit-scrollbar-thumb {
            background-color: var(--border-color);
            border-radius: 4px;
        }
        
        #id-list::-webkit-scrollbar-thumb:hover {
            background-color: var(--accent-primary);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>剪映草稿片段乱序工具</h1>

        <div class="section">
            <label for="directory-path">草稿目录:</label>
            <div class="directory-input-container">
                <input type="text" id="directory-path" readonly placeholder="点击按钮选择目录">
                <button id="select-dir-btn">选择目录</button>
            </div>
        </div>

        <div class="section">
            <h2>当前片段顺序 (Segment ID 或 Material ID):</h2>
            <ul id="id-list">
                <li>请先选择目录</li>
            </ul>
        </div>

        <div class="section">
            <button id="randomize-btn" disabled>随机打乱片段顺序并保存</button>
        </div>

        <div class="section">
            <p id="status-message">等待操作...</p>
        </div>
    </div>

    <script>
        // --- JavaScript for pywebview --- 
        const selectDirBtn = document.getElementById('select-dir-btn');
        const directoryPathInput = document.getElementById('directory-path');
        const idListUl = document.getElementById('id-list');
        const randomizeBtn = document.getElementById('randomize-btn');
        const statusMessageP = document.getElementById('status-message');

        let currentDirectoryPath = null; // Store the confirmed path from Python

        // --- 更新状态信息 (called by Python) ---
        function updateStatus(message, isError = false, isProcessing = false) {
            console.log("Status update:", message, "Error:", isError);
            statusMessageP.textContent = message;
            
            // Reset all status classes
            statusMessageP.classList.remove('status-error', 'status-processing');
            
            // Apply appropriate class based on state
            if (isError) {
                statusMessageP.classList.add('status-error');
            } else if (isProcessing) {
                statusMessageP.classList.add('status-processing');
            }
        }

        // --- 重命名并修改：更新片段信息显示 ---
        function displaySegmentInfo(segmentInfos) {
            idListUl.innerHTML = '';
            if (segmentInfos && segmentInfos.length > 0) {
                segmentInfos.forEach((info, index) => {
                    if (info && info.id) {
                         const li = document.createElement('li');
                         // 显示序号和 ID
                         li.textContent = `${info.id}`; // 只显示 ID 可能更简洁
                         // 或者显示序号: li.textContent = `${index + 1}. ${info.id}`;
                         idListUl.appendChild(li);
                    } else {
                         console.warn("Received invalid segment info item:", info);
                    }
                });
                randomizeBtn.disabled = !currentDirectoryPath;
            } else {
                const li = document.createElement('li');
                li.textContent = currentDirectoryPath ? '未找到片段信息' : '请先选择有效目录';
                idListUl.appendChild(li);
                randomizeBtn.disabled = true;
            }
        }

        // --- 设置目录路径 (called by Python after dialog) ---
        function setDirectoryPath(path) {
             console.log("Python set directory path:", path);
             if (path) {
                 currentDirectoryPath = path;
                 directoryPathInput.value = path;
                 // Python 会自动调用 load_segment_info, 这里无需调用
                 // randomizeBtn.disabled = false; // 由 displaySegmentInfo 控制
             } else {
                 // Clear path if Python indicates failure or cancellation
                 currentDirectoryPath = null;
                 directoryPathInput.value = '';
                 directoryPathInput.placeholder = '点击按钮选择目录';
                 displaySegmentInfo([]); // 使用新函数清空列表
                 randomizeBtn.disabled = true;
             }
        }

         // --- 处理完成回调 (called by Python) ---
         function processingComplete(success) {
              // Re-enable randomize button regardless of success/failure,
              // as long as a directory is selected.
              randomizeBtn.disabled = !currentDirectoryPath;
              console.log("Processing complete callback, success:", success);
              // Status is already updated by Python
         }

        // --- Event Listeners ---

        // 选择目录按钮点击事件 (Calls Python API)
        selectDirBtn.addEventListener('click', function() {
            updateStatus('正在打开目录选择器...', false, true);
            randomizeBtn.disabled = true; // Disable while selecting
            idListUl.innerHTML = '<li>...</li>'; // Indicate loading/waiting
            
            // Call Python API to trigger the native dialog
            if (window.pywebview && window.pywebview.api) {
                window.pywebview.api.trigger_directory_dialog()
                    .catch(error => {
                        console.error('Error calling Python trigger_directory_dialog:', error);
                        updateStatus(`请求目录选择出错: ${error}`, true);
                        randomizeBtn.disabled = !currentDirectoryPath; // Re-enable based on current path status
                    });
            } else {
                console.error('pywebview API not available');
                updateStatus('错误: Python API 未加载，请刷新页面或检查应用配置', true);
            }
        });

        // 随机化按钮点击事件 (Calls Python API)
        randomizeBtn.addEventListener('click', function() {
            if (!currentDirectoryPath) {
                updateStatus('错误：请先选择一个包含所需文件的有效目录！', true);
                return;
            }
            updateStatus('开始随机化片段顺序...', false, true);
            randomizeBtn.disabled = true; // Disable during processing
            
            if (window.pywebview && window.pywebview.api) {
                window.pywebview.api.randomize_ids()
                    .catch(error => {
                        console.error('Error calling Python randomize_ids:', error);
                        updateStatus(`调用随机化功能时出错: ${error}`, true);
                        randomizeBtn.disabled = false; // Re-enable on error
                    });
            } else {
                console.error('pywebview API not available');
                updateStatus('错误: Python API 未加载，请刷新页面或检查应用配置', true);
                randomizeBtn.disabled = false;
            }
        });

        // --- Initial Setup ---
        // Expose functions needed by Python
        window.updateStatus = updateStatus;
        window.displaySegmentInfo = displaySegmentInfo;
        window.setDirectoryPath = setDirectoryPath;
        window.processingComplete = processingComplete;

        // Check if pywebview is ready
        document.addEventListener('DOMContentLoaded', function() {
            // If pywebviewready event is supported
            window.addEventListener('pywebviewready', () => {
                console.log('pywebview is ready');
                updateStatus('应用已准备就绪，请点击"选择目录"按钮。');
            });
            
            // Fallback if the event doesn't fire
            setTimeout(function() {
                if (!window.pywebview || !window.pywebview.api) {
                    console.warn('pywebview API not detected after timeout');
                    updateStatus('警告: Python API 可能未正确加载，但您仍可尝试使用功能', false);
                }
            }, 2000);
        });

        // Initial status message
        updateStatus('请点击"选择目录"按钮。');
    </script>
</body>
</html>
